<?php
namespace app\admin\controller;
use think\Controller;

Class User extends BaseAdmin
{

	//会员列表
    public function lst()
    {
    	
        
        $UserRes=db('tp_user')->paginate(5);
        $this->assign('UserRes',$UserRes);
        // dump($data->render());
        // exit;
        return $this->fetch('list');
    }

    //会员添加
    public function add()
    {
        $memberLevel=db('tp_member_level')->select();
        $this->assign('memberLevel',$memberLevel);
    	 
        if(request()->isPost()){
        	$data=input('post.');
            $data['password']=md5($data['password']);
            $data['register_time']=time();

            //验证
            $validate = new \app\admin\validate\User;
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
        	
        	$add=db('tp_user')->insert($data);
        	if($add){
        		$this->success('保存成功','lst');
        	}
        	else{
        		$this->error('保存失败');
        	}

        }
        return $this->fetch();

    }

    //会员编辑
    public function edit($id)
    {
    	$UserRes=db('tp_user')->where(array('id'=>$id))->find();
    	$this->assign('UserRes',$UserRes);
    	if(request()->isPost()){
        	$data=input('post.');
            //验证
            $validate = new \app\admin\validate\User;
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
        	$up=db('tp_user')->where(array('id'=>$id))->update($data);
        	// dump($up);
        	// exit;
        	if($up!==false){
        		$this->success('保存成功','lst');
        	}
        	else{
        		$this->error('保存失败');
        	}

        }
        return $this->fetch();
    }

    //会员删除
    public function del($id)
    {

        $userOrder=db('tp_order')->where(array('user_id'=>$id))->select();//改会员的订单信息
        foreach ($userOrder as $k => $v) {
            $orderGoods=db('tp_order_goods')->where('order_id',$v['id'])->delete();//删除订单中商品信息
        }
        db('tp_order')->where(array('user_id'=>$id))->delete();//删除会员订单
    	$del=db('tp_user')->delete($id);
    	if($del){
    		$this->success('删除成功','lst');

    	}else{
            $this->error('删除失败');
    	}
    	
        return $this->fetch();
    }

    
    //图片上传
	public function upload(){
		$file=request()->file('brand_img');
		if($file==null){
			exit(json_encode(array('msg'=>'没有文件上传')));
		}
		$info=$file->move('../public/static/uploads');
		$ext=$info->getExtension();//获取后缀名
		if(!in_array($ext,array('jpg','png','gif','jpeg'))){
			exit(json_encode(array('msg'=>'文件格式不符合')));
		}
		if($info){
			return $img=$info->getSaveName();

		}else{
			$file->getError();
			die;
		}
		
		
	}


}